<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\Brand\Extensions\Tools\BatchClaimBrandContent;
use Biz\model\brand\Brand;
use Biz\model\brand\Content as mBrandContent;
use Biz\service\wiki\WikiContent;
use Biz\tools\RealUrl;
use Doraemon\tools\HhzEnv;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Tools\BatchActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;

class WikiContentController extends Controller
{
    const PAGE_SIZE = 20;
    const SOURCE_CATEGORY_LIST = '/admin/extend/category/child';

    const STATE_MAP = [
        0 => '待审核',
        1 => '审核通过',
        2 => '审核不通过',
    ];

    /**
     * 搜索条件
     * @param Grid $grid
     */
    public function listFilter(Grid $grid, $condition)
    {
        //品牌 ID / 品牌名称 / 品牌身份（认证品牌/精选品牌/超级品牌）/
        //认领类型（仅认领内容 / 认领商品 / 仅关联商品 / 认领内容并关联商品）/商品数量/内容类型（图片/视频Note、文章、整屋案例 ）/审核状态（待审核 / 审核未通过）
        $grid->filter(function (Grid\Filter $filter) use ($condition) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function (Grid\Filter $filter) use ($condition) {
                $filter->equal('brand_id', '品牌 ID');
                $filter->equal('brand_name', '品牌名称');
                $filter->equal('brand_type', '品牌身份')->select(Brand::ADM_BRAND_TYPE);
                $filter->equal('search_keywords', '检索词类型')->multipleSelect(Brand::SEARCH_BRAND_TYPE)->default($condition['search_keywords']);
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('claim_type', '认领类型')->select(\Biz\model\brand\Content::CLAIM_TYPE_MAP);
                $filter->equal('type_desc', '内容类型')->select(WikiContent::OBJ_TYPE);
                $filter->equal('audit_status', '审核状态')->select(\Biz\model\brand\Content::AUDIT_MAP);
            });
            $filter->expand();
        });
    }

    private function _getExpand($v)
    {
        $row = new Row();
        if (!empty($v['wiki_list'])) {
            $id = $v['id'];
            $claim_type = $v['claim_type'];
            $GirdModel = new pGridDataModel($v['wiki_list'], null, ['pageName' => '']);
            $grid = new Grid($GirdModel);
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disableTools();
            $grid->disableExport();


            switch ($claim_type) {
                case \Biz\model\brand\Content::CLAIM_TYPE_APPEND_ONLY:
                case \Biz\model\brand\Content::CLAIM_TYPE_BOTH:
                    $grid->column('claim_wiki_id', '品牌商品')->display(function () {
                        $claim_wiki_info = $this->claim_wiki_info;
                        $h5_url = HhzEnv::detectShopDomain() . 'shop/goods-detail/wiki?wiki_id=' . $claim_wiki_info['id'] . '&no-pc-redirect=true';
                        $html = [
                            "<b>头图:</b>" . "<img src='" . ($claim_wiki_info['cover_img'] ?? '') . "' style='width:100px' class='img img-thumbnail' />",
                            "<b>查看 Wiki 详情:</b>" . '<a class="fa fa-chain" href="javascript:layer.open({
                                type: 2,
                                title: \'第三方链接\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $h5_url . '\'
                            });">链接</a>',
                            "<b>商品名称:</b>" . $claim_wiki_info['title'] ?? '',
                        ];
                        return "<div style='width: 400px'>" . implode("<br/>", $html) . "</div>";
                    });
                    break;
                case \Biz\model\brand\Content::CLAIM_TYPE_WIKI_ONLY:
                    $grid->column('wiki_id', '已关联商品')->display(function () {
                        $wiki_info = $this->wiki_info;
                        $url = RealUrl::formatLink($wiki_info['channel_spu_id'], $wiki_info['channel_type']);
                        $html = [
                            "<b>头图:</b>" . "<img src='" . ($wiki_info['cover_img'] ?? '') . "' style='width:100px' class='img img-thumbnail' />",
                            "<b>第三方网站查看:</b>" . '<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'1000px\', \'500px\'],
                                content: \'' . $url . '\'
                            });">预览</a>',
                            "<b>商品名称:</b>" . $wiki_info['title'] ?? '',
                        ];
                        return "<div style='width: 400px'>" . implode("<br/>", $html) . "</div>";
                    });
                    $grid->column('claim_wiki_id', '品牌商品')->display(function () {
                        $claim_wiki_info = $this->claim_wiki_info;
                        $h5_url = HhzEnv::detectShopDomain() . 'shop/goods-detail/wiki?wiki_id=' . $claim_wiki_info['id'] . '&no-pc-redirect=true';
                        $html = [
                            "<b>头图:</b>" . "<img src='" . ($claim_wiki_info['cover_img'] ?? '') . "' style='width:100px' class='img img-thumbnail' />",
                            "<b>查看 Wiki 详情:</b>" . '<a class="fa fa-chain" href="javascript:layer.open({
                                type: 2,
                                title: \'第三方链接\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $h5_url . '\'
                            });">链接</a>',
                            "<b>商品名称:</b>" . $claim_wiki_info['title'] ?? '',
                        ];
                        return "<div style='width: 400px'>" . implode("<br/>", $html) . "</div>";
                    });
                    break;
            }


            $grid->column('audit_status', '审核状态')->using(\Biz\model\brand\Content::AUDIT_MAP);

            if (in_array($claim_type, [\Biz\model\brand\Content::CLAIM_TYPE_CONTENT_ONLY])) {
                $grid->disableActions();
            } else {
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($id) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->prepend('&nbsp;<a class="fa pass-data" data-id="' . $id . '"  data-wid="' . $actions->row->id . '" href="javascript:void(0);">审核通过</a>');

                    if ($this->row->audit_status != \Biz\model\brand\Content::AUDIT_STATUS_REJECT) {
                        $actions->prepend('&nbsp;<a class="fa not-pass-data" data-id="' . $id . '" data-wid="' . $actions->row->id . '" href="javascript:void(0);">审核不通过</a>');
                    }
                });
            }
            $grid->disablePagination();
            $row->column('12', $grid);
            return $row->render();
        }
        return '';
    }

    public function list(Request $request, Content $content)
    {
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $condition = self::getCondition($request->all());
        $list = WikiContent::admPagedList($condition, $page, $page_size);
        foreach ($list['list'] as &$item) {
            $item['expand'] = $this->_getExpand($item);
        }
        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $page_size
        ]);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $condition) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableCreateButton();

                $grid->tools(function (Grid\Tools $tools) {
                    $tools->batch(function (BatchActions $batch) {
                        $batch->disableDelete();
                        $batch->add('批量审核', new BatchClaimBrandContent(1));
                    });
                });

                //筛选条件
                $this->listFilter($grid, $condition);

                $grid->column("id")->expand(function () {
                    return $this->expand;
                }, true)->width(80);
                $grid->column('brand_logo', '品牌 Logo')->image('', 80);
                $grid->column('brand_info', '品牌信息')->display(function () {
                    $html = [
                        "<b>品牌 ID:</b>" . $this->brand_id,
                        "<b>品牌名称:</b>" . $this->brand_name,
                        "<b>品牌身份:</b>" . Brand::BRAND_TYPE[$this->brand_type],

                    ];
                    return implode("<br/>", $html);
                });
                $grid->column('info', '内容')->display(function () {
                    $info = $this->info;
                    $html = [
                        "<b>内容标题:</b>" . $info['title'] ?? '',
                        "<b>正文:</b>" . mb_substr($info['content'] ?? '', 0, 100),
                        "<b>图片:</b>" . "<img src='" . ($info['cover_pic_url'] ?? '') . "' style='width:100px' class='img img-thumbnail' />",
                        "<b>查看内容详情:</b>" . '<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'1000px\', \'500px\'],
                                content: \'' . WikiContent::contentPreView($info['id']) . '\'
                            });">预览</a>',
                    ];
                    return "<div style='width: 300px'>" . implode("<br/>", $html) . "</div>";
                });

                $grid->column('words', '检索词')->display(function ($words) {
                    $words = $words ? json_decode($words, true) : [];
                    if (!$words['brand_alias'] && !$words['brand_name']) {
                        $words['warning'] = "<b style='color: #ff0000;font-size: 10px;'> *该内容未命中品牌词</b>";
                    }
                    $html = [
                        $words['brand_name'] ? "<b>品牌名称:</b>" . implode(',', $words['brand_name']) : '',
                        $words['brand_alias'] ? "<b>品牌别称:</b>" . implode(',', $words['brand_alias']) : '',
                        $words['search_keywords'] ? "<b>其他:</b>" . implode(',', $words['search_keywords']) : '',
                        $words['warning'] ?: '',
                    ];
                    return "<div style='width: 300px'>" . implode("<br/>", $html) . "</div>";
                });


                $grid->column('claim_type', '认领类型')->using(\Biz\model\brand\Content::CLAIM_TYPE_MAP);
                $grid->column('wiki_num', '商品数量');
                $grid->column('type_desc', '内容类型');
                $grid->column('audit_status', '审核状态')->using(\Biz\model\brand\Content::AUDIT_MAP);

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    if (in_array($this->row->claim_type, [\Biz\model\brand\Content::CLAIM_TYPE_CONTENT_ONLY])) {
                        $actions->prepend('&nbsp;<a class="fa pass-data"  data-id="' . $actions->row->id . '" href="javascript:void(0);">审核通过</a>');

                        if ($this->row->audit_status != \Biz\model\brand\Content::AUDIT_STATUS_REJECT) {
                            $actions->prepend('&nbsp;<a class="fa not-pass-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">审核不通过</a>');
                        }
                    }
                });
            }
        );
        $tab = new Tab();
        $header = '认领/关联审核';
        $tab->add($header, $gridList->render());
        $content->row($tab);

        Admin::script(self::auditScript());

        return $content
            ->header($header)
            ->description(' ')
            ->breadcrumb(['text' => $header]);
    }

    public function reject(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $id = $request->input('id', 0);
            $wid = $request->input('wid', 0);
            $reason = $request->input('reason', '');
            $content = $request->input('content', '0');

            WikiContent::auditReject($id, $wid, $reason, $content, $adminId);

            $success = [
                'title' => '操作成功',
                'code' => 1
            ];

        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function audit(Request $request)
    {
        try {
            $adminId = Admin::user()->id;

            $ids = $request->input('ids', []);

            //检查内容是否存在
            $content = mBrandContent::select('*', [
                'id' => $ids,
            ]);

            $msg = '';
            if (!empty($content)) {
                foreach ($content as $v) {
                    if ($v['claim_type'] == mBrandContent::CLAIM_TYPE_CONTENT_ONLY) {
                        try {
                            WikiContent::audit($v['id'], 0, $adminId);
                            $msg .= $v['id'] . "操作成功<br/>";
                        } catch (\Exception $e) {
                            $msg .= $v['id'] . "操作失败,{$e->getMessage()}<br/>";
                        }
                    } else {
                        $msg .= $v['id'] . "的认领类型不支持批量操作<br/>";
                    }
                }
            } else {
                $id = $request->input('id', 0);
                $wid = $request->input('wid', 0);
                $wid = $wid > 0 ? $wid : 0;
                WikiContent::audit($id, $wid, $adminId);
            }


            $success = [
                'title' => $msg ?? '操作成功',
                'code' => 1
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function unPass(Request $request, \App\Admin\Extensions\WorkContent $content, $id, $wid)
    {
        Admin::script(self::unPassScript());
        $form = new Form(['id' => $id, 'wid' => $wid]);
        $form->attribute('class', 'unpass');
        $form->hidden('id');
        $form->hidden('wid');
        $rs = \Biz\model\brand\Content::get('*', ['id' => $id]);
        $claim_type = $rs['claim_type'];
        $content_status = $rs['content_status'];
        if ($claim_type == \Biz\model\brand\Content::CLAIM_TYPE_BOTH) {
            if ($content_status == \Biz\model\brand\Content::CLAIM_MATCH) {
                $form->checkbox('content', '内容不属于该品牌')->options([1 => '是']);
            } else {
                $form->checkbox('content', '内容不属于该品牌')->options([1 => '是'])->default(1)->disable();
            }
        }
        $form->textarea('reason', '原因');
        $form->html('<div class="col-md-8"><div class="btn-group pull-right"><button type="button" class="btn btn-info pull-right btn-unpass">确定</button></div></div>');
        $form->disableSubmit();
        $form->disableReset();
        return $content->body($form);
    }

    private static function getCondition($request)
    {
        $condition = [];

        if (!empty($request['brand_id'])) {
            $condition['brand_id'] = $request['brand_id'];
        }
        if (!empty($request['brand_name'])) {
            $brand_id = Brand::get('id', ['brand_name' => $request['brand_name']]);
            $condition['brand_id'] = $brand_id;
        }
        if (!empty($request['brand_type'])) {
//            $condition['brand_type'] = $request['brand_type'];
        }

        if (isset($request['audit_status']) && $request['audit_status'] !== '') {
            $condition['audit_status'] = $request['audit_status'];
        }

        if (!empty($request['type_desc'])) {
            $condition['obj_type'] = $request['type_desc'];
        }

        if (!empty($request['claim_type'])) {
            $condition['claim_type'] = $request['claim_type'];
        }

        if (!empty($request['search_keywords'])) {
            $condition['search_keywords'] = $request['search_keywords'];
        }
        return $condition;
    }

    private function auditScript()
    {
        return <<<SCRIPT
        $('.pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
           var wid= $(this).data('wid');
            let url = 'audit'
            let params = {id:id, wid:wid}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    toastr.success(result.title, null, {
                        timeOut : 1000
                    }); 
                    setTimeout(function () {
                        $.pjax.reload('#pjax-container');
                    }, 1000);
                } else {
                    toastr.error(result.title, null, {
                        timeOut : 3000
                    }); 
                }
            });
        });
        $('.not-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var wid= $(this).data('wid');
            layer.open({
                type: 2,
                title: '审核不通过',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '400px'],
                content: 'audit/'+id+'/unPass/'+ wid
            });
        });
         
SCRIPT;
    }

    private function unPassScript()
    {
        return <<<SCRIPT
        $('.btn-unpass').unbind('click').click(function(){
            var id= $('input[name="id"]').val();
            var wid= $('input[name="wid"]').val();
            var reason=$('textarea[name="reason"]').val();
            var content=$(':input[name="content[]"]:checked').val();
            let params = {id:id,wid:wid,reason:reason,content:content}
            $.post('', params , function (result) {
                if (result.code == 1) {
                    toastr.success(result.title, null, {
                        timeOut : 1000
                    }); 
                    setTimeout(function () {
                        $.pjax.reload('#pjax-container');
                    }, 1000);
                } else {
                    toastr.error(result.title, null, {
                        timeOut : 3000
                    }); 
                }
            });
        });
SCRIPT;
    }
}
